<template>
  <div v-if="proxy.isAuth(['ROOT', 'ORDER:SELECT'])">
    <el-form :inline="true" :model="dataForm" :rules="dataRule" ref="form">
      <el-form-item prop="code">
        <el-input class="input" maxlength="20" v-model="dataForm.code" placeholder="套餐编号" clearable/>
      </el-form-item>
      <el-form-item prop="keyword">
        <el-input class="keyword" maxlength="50" v-model="dataForm.keyword" placeholder="套餐名称" clearable/>
      </el-form-item>
      <el-form-item prop="tel">
        <el-input class="input" maxlength="11" v-model="dataForm.tel" placeholder="电话号码" clearable/>
      </el-form-item>
      <el-form-item prop="range">
        <el-date-picker v-model="dataForm.dateRange" type="daterange" range-separator="~" start-placeholder="起始日期"
                        end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD"/>
      </el-form-item>
      <el-form-item>
        <el-select v-model="dataForm.status" class="status" placeholder="订单状态" clearable style="width: 100px;">
          <el-option label="未付款" value="1"/>
          <el-option label="已关闭" value="2"/>
          <el-option label="已付款" value="3"/>
          <el-option label="已退款" value="4"/>
          <el-option label="已预约" value="5"/>
          <el-option label="已结束" value="6"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchHandle" style="margin-right: 20px">查询</el-button>
        <el-button type="primary" v-if="proxy.isAuth(['ROOT', 'ORDER:UPDATE'])" :icon="Refresh"
                   @click="checkPaymentResultHandle">同步付款结果
        </el-button>
      </el-form-item>
    </el-form>
    <el-table :data="data.dataList" :header-cell-style="{'background': '#f5f7fa'}" border v-loading="data.loading" @selection-change="selectionChangeHandle" @expand-change="expand" :expand-row-keys="data.expands" :row-key="data.getRowKeys">
      <el-table-column type="expand">

        <template #default="scope">
          <!--折叠面板-->
          <div class="content-container">
            <div class="left-panel">
              <el-card class="box-card" shadow="never">
                <div class="info">
                  <div class="left">
                    <el-avatar :size="57" shape="square" :src="scope.row.photo"></el-avatar>
                    <el-icon size="35">
                      <UserFilled/>
                    </el-icon>
                  </div>
                  <div class="right">
                    <h4 class="customer-name">{{ scope.row.name }}</h4>
                    <p class="customer-desc">
                      <el-icon class="icon"><User /></el-icon>
                      <span class="value">{{scope.row.sex}}</span>
                      <el-icon class="icon"><Phone /></el-icon>
                      <span class="value">{{scope.row.tel}}</span>
                      <el-icon class="icon"><Calendar/></el-icon>
                      <span class="value">{{scope.row.registerTime}}</span>
                    </p>
                  </div>
                </div>
                <el-divider/>
                <el-row :gutter="16">
                  <el-col :span="6">
                    <div class="statistic-card">
                      <el-statistic :value="scope.row.number - scope.row.num" suffix="个">
                        <template #title>
                          <div class="title">可预约体检</div>
                        </template>
                      </el-statistic>
                    </div>
                  </el-col>
                  <el-col :span="6">
                    <div class="statistic-card">
                      <el-statistic :value="scope.row.num" suffix="个">
                        <template #title>
                          <div class="title">已预约体检</div>
                        </template>
                      </el-statistic>
                    </div>
                  </el-col>
                  <el-col :span="6">
                    <div class="statistic-card">
                      <el-statistic :value="scope.row.number" suffix="个">
                        <template #title>
                          <div class="title">总计数量</div>
                        </template>
                      </el-statistic>
                    </div>
                  </el-col>
                </el-row>
              </el-card>
              <el-descriptions :column="1" class="order-code" border>
                <template #default>
                  <el-descriptions-item label="订单编号" label-align="center">
                    {{scope.row.outTradeNo}}
                  </el-descriptions-item>
                  <el-descriptions-item label="付款编号" label-align="center">
                    {{scope.row.transactionId == null ? "无" : scope.row.transactionId}}
                  </el-descriptions-item>
                  <el-descriptions-item label="退款编号" label-align="center">
                    {{scope.row.outRefundNo == null ? "无" : scope.row.outRefundNo}}
                  </el-descriptions-item>
                </template>
              </el-descriptions>
            </div>
            <div class="right-panel">
              <el-table :data="data.appointment" :header-cell-style="{'background' : '#f5f7fa'}" height="350" border>
                <el-table-column label="序号" type="index" label-align="center" align="center" min-width="90">
                  <template #default="scope">
                    <span>{{ scope.$index + 1}}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="name" label="体检人" label-align="center" align="center" min-width="180"/>
                <el-table-column prop="sex" label="性别" label-align="center" align="center" min-width="120"/>
                <el-table-column prop="age" label="年龄" label-align="center" align="center" min-width="120"/>
                <el-table-column prop="tel" label="电话" label-align="center" align="center" min-width="180"/>
                <el-table-column prop="date" label="体检日" label-align="center" align="center" min-width="180"/>
                <el-table-column prop="status" label="状态" label-align="center" align="center" min-width="130"/>
              </el-table>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column type="selection" header-align="center" width="50" align="center" :selectable="selectable"/>
      <el-table-column prop="index" header-align="center" align="center" label="序号" width="60">
        <template #default="scope">
          <span>{{ (data.pageIndex - 1) * data.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="goodsTitle" header-align="center" align="left" label="套餐名称" min-width="120"/>
      <el-table-column header-align="center" align="center" label="价格" min-width="80">
        <template #default="scope">
          <span>¥{{ scope.row.goodsPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="number" header-align="center" align="center" label="数量" width="100"/>
      <el-table-column header-align="center" align="center" label="总计" min-width="100">
        <template #default="scope">
          <span>¥{{ scope.row.amount }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" header-align="center" align="center" label="状态" width="100"/>
      <el-table-column prop="createTime" header-align="center" align="center" label="下单时间" width="180"/>
      <el-table-column prop="refundTime" header-align="center" align="center" label="退款时间" width="180" />
      <el-table-column header-align="center" align="center" label="操作" width="260">
        <template #default="scope">
          <el-button v-if="proxy.isAuth(['ROOT', 'ORDER:SELECT'])" type="primary" @click="viewHandle(scope.row.snapshotId)">预览</el-button>
          <el-button v-if="proxy.isAuth(['ROOT', 'ORDER:DELETE'])" type="primary" @click="deleteHandle(scope.row.id)" :disabled="scope.row.status != '已关闭'">删除</el-button>
          <el-button v-if="proxy.isAuth(['ROOT', 'ORDER:UPDATE'])" type="primary" @click="updateHandle(scope.row.id)" :disabled="scope.row.status != '已付款'">线下退款</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="data.pageIndex"
        :page-sizes="[10, 20, 30]"
        :page-size="data.pageSize"
        :total="data.totalCount"
        style="margin-top: 20px;"
        layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>
  </div>
</template>

<script setup lang="ts">
import {ref, reactive, onMounted, Ref, getCurrentInstance} from 'vue'
import router from '../../router/index.ts'
import {Phone, Refresh, UserFilled, User, Calendar} from "@element-plus/icons-vue";

const {proxy} = getCurrentInstance();

const dataForm = reactive({
  keyword: null,
  code: null,
  tel: null,
  dateRange: [],
  status: null
});

const dataRule = reactive({
  code: [
    {
      min: 6,
      message: '套餐编号长度不能小于6位'
    },
    {
      pattern: '^[a-zA-Z0-9]{6,20}$',
      message: '套餐编号只能由6-20位字母和数字组成'
    }
  ],
  keyword: [
    {
      pattern: '^[a-zA-Z0-9\u4e00-\u9fa5]{1,50}$',

      message: '套餐名称只能由1-50位字母、数字或汉字组成'
    }
  ],
  tel: [
    {
      pattern: '^1[1-9]\\d{9}$',
      message: '电话号码格式不正确'
    }
  ]
});

const data = reactive({
  dataList: [
    {
      amount: "3,377",
      snapshotId: "631239das31193123jead123",
      registerTime: "2023-03-18",
      sex: "男",
      num: 0,
      photo: "",
      number: 1,
      createTime: "2023-08-04 12:37",
      goodsPrice: "3,377",
      outTradeNo: '44DCED2D0FC34EA498C647E565D5D3D',
      name: '马梓濠',
      goodsTitle: '新感恩敬老高级体检套餐',
      tel: '15088160276',
      id: 87,
      status: '已关闭',
      createDate: '2023-08-04'
    }
  ],
  loading: false,
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
  selection: [],
  expands: [],
  getRowKeys(row) {
    return row.id;
  },
  appointment: []
});

/**
 * 加载分页数据处理函数
 */
function loadDataList() {
  data.loading = true;
  let range = dataForm.dateRange
  let json = {
    page: data.pageIndex,
    length: data.pageSize,
    keyword: dataForm.keyword,
    code: dataForm.code,
    tel: dataForm.tel,
    status: dataForm.status,
    startDate: (range != null && range.length == 2) ? range[0] : null,
    endDate: (range != null && range.length == 2) ? range[1] : null
  };
  proxy.$http('/mis/order/searchByPage', 'POST', json, true, resp => {
    let statusEnum = {
      "1": "未付款",
      "2": "已关闭",
      "3": "已付款",
      "4": "已退款",
      "5": "已预约",
      "6": "已结束"
    }
    let page = resp.page;
    let list = page.list;
    for (let one of list) {
      one.status = statusEnum[one.status + ""]
    }
    data.dataList = list;
    console.log(data.dataList);
    data.totalCount = page.totalCount;
    data.loading = false;
  });
}

loadDataList();

/**
 * 按照条件查询处理函数
 */
function searchHandle() {
  proxy.$refs['form'].validate(valid => {
    if (valid) {
      proxy.$refs['form'].clearValidate();
      if (dataForm.keyword == '') {
        dataForm.keyword = null;
      }
      if (dataForm.code == '') {
        dataForm.code = null;
      }

      if (dataForm.tel == '') {

        dataForm.tel = null;
      }
      if (dataForm.status == '') {

        dataForm.status = null;
      }
      if (data.pageIndex != 1) {

        data.pageIndex = 1;
      }
      loadDataList();
    } else {
      return false;
    }
  });
}

// 分页控件相关函数
function sizeChangeHandle(val) {
  data.pageIndex = 1;
  data.pageSize = val;
  loadDataList();
}
// 分页控件相关函数
function currentChangeHandle(val) {
  data.pageIndex = val;
  loadDataList();
}

// 订单记录展开和折叠触发的回调函数 row:订单记录 expandedRows:数组
function expand(row, expandedRows) {
  if (expandedRows.length > 0) {
    // 先把所有展开的面板收起
    data.expands = [];
    if (row) {
      data.appointment = [];
      let json = {
        // 参数:当前订单id
        orderId: row.id
      }
      proxy.$http('/mis/appointment/searchByOrderId', 'POST', json, true, resp => {
        let result = resp.result;
        // 把数字改为对应的文字
        let statusEnum = {
          "1": "未签到",
          "2": "已签到",
          "3": "已结束",
          "4": "已关闭"
        }
        for (let one of result) {
          one.status = statusEnum[one.status + ""];
        }
        data.appointment = result;
      })
      // 展开订单记录的折叠面板
      data.expands.push(row.id);
    } else {
      data.expands = [];
    }
  }
}

// 删除订单按钮回调函数
function deleteHandle(id) {
  proxy.$confirm('确定要删除该订单吗?', '提示', {
    confirmButtonText: '确定',

    cancelButtonText: '取消',

    type: 'warning'
  }).then(() => {
    let json = {
      "id": id
    }
    proxy.$http('/mis/order/deleteById', 'POST', json, true, resp => {
      if (resp.rows > 0) {
        proxy.$message({
          message: '删除成功',
          type: 'success',
          duration: 1200,
          onClose: () => {
            loadDataList();
          }
        });
      } else {
        proxy.$message({
          message: '删除失败',
          type: 'warning',
          duration: 1200
        });
      }
    });
  });
}

// 线下退款按钮回调函数
function updateHandle(id) {
  proxy.$confirm('确认订单已经线下退款成功?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    let json = {
      "id": id
    }
    proxy.$http('/mis/order/updateRefundOrderStatusById', 'POST', json, true, resp => {
      if (resp.rows > 0) {
        proxy.$message({
          message: '更新成功',
          type: 'success',
          duration: 1200,
          onClose: () => {
            loadDataList();
          }
        });
      } else {
        proxy.$message({
          message: '更新失败',
          type: 'warning',
          duration: 1200
        });
      }
    });
  });
}

</script>

<style scoped lang="less">
@import url('order.less');
</style>